package com.djsearch.ui;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.djsearch.R;
import com.djsearch.bean.GroupBuyGoods;
import com.djsearch.bean.Movie;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.data.ImageManager;
import com.djsearch.util.AsyncImageLoader;
import com.djsearch.util.AsyncImageLoader.ImageCallback;

public class MovieDetailsActivity extends BaseActivity{

	private TextView describe,address,phoneNumText,
	personsBuyText,nowPriceText,oldPriceText;//商品描述,地址,电话,购买人数,现在价格（打折后价格）,原来价格
	private LinearLayout shouChangLayout,shareLayout,taoGouLayout;//收藏  分享 淘购
	private LinearLayout linearLayoutOne;
	private ImageView goodsImg;
	private Button lookBtn,locationBtn;//去看看按钮,定位按钮
	private Button backBtn;
	private Context mContext;
	private Movie movieBean;
	private AsyncImageLoader asyncImageLoader;
	private ProgressBar progressBar;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.movie_details_layout);
		mContext = this;
		movieBean = (Movie)getIntent().getSerializableExtra("data");
		asyncImageLoader = new AsyncImageLoader("bigPic");
		//得到屏幕的分辨率
		getDisPlayMetrics();
		//初始化主界面
		initView();
		//初始化主界面相关点击事件
		initOnClick();
		//初始化handler
		initHandler();
	}
	
	@Override
	void initHandler() {
		// TODO Auto-generated method stub
		
	}

	@Override
	void initView() {
		// TODO Auto-generated method stub
		backBtn = (Button)findViewById(R.id.btnBack);
		
		locationBtn = (Button)findViewById(R.id.btndingwei);
		if (movieBean.getLatitude().equals("") ||
				movieBean.getLongitude().equals("")) {
			locationBtn.setVisibility(View.GONE);
		}
		locationBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				double locInfo[] = new double[2];
				locInfo[0] = Double.parseDouble(movieBean.getLatitude());
				locInfo[1] = Double.parseDouble(movieBean.getLongitude());
				Intent intent = new Intent(mContext,LocInfoActivity.class);
				Bundle bundle = new Bundle();
				bundle.putDoubleArray("locinfo", locInfo);
				intent.putExtras(bundle);
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			}
		});
		
		lookBtn = (Button)findViewById(R.id.toLookBtn);
		describe = (TextView)findViewById(R.id.describe);
		address = (TextView)findViewById(R.id.locationInfoText);
		address.setText(movieBean.getPlace());
		phoneNumText = (TextView)findViewById(R.id.phoneNumText);
		phoneNumText.setText(movieBean.getTelephone());
		personsBuyText = (TextView)findViewById(R.id.personsBuyText);
		personsBuyText.setText(movieBean.getHasBuy()+"人购买");
		linearLayoutOne = (LinearLayout)findViewById(R.id.linearLayoutOne);
		progressBar = (ProgressBar)findViewById(R.id.progressBar);
		goodsImg = (ImageView)findViewById(R.id.goodsImg);
        asyncImageLoader.loadDrawable(progressBar,goodsImg,movieBean.getBigImage(), new ImageCallback() {
			@Override
			public void imageLoaded(ProgressBar progressBar,ImageView imageView,Drawable imageDrawable, String imageUrl, String tag) {
				// TODO Auto-generated method stub
				goodsImg.setImageBitmap(ImageManager.drawableToBitmap(imageDrawable,464.0f));
				progressBar.setVisibility(View.GONE);
			}
		});
        
        shouChangLayout = (LinearLayout)findViewById(R.id.shouChangLayout);
        shareLayout = (LinearLayout)findViewById(R.id.shareLayout);
        taoGouLayout = (LinearLayout)findViewById(R.id.taoGouLayout);
        
	}

	@Override
	void initOnClick() {
		// TODO Auto-generated method stub
        backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			startActivity(mContext, MovieActivity.class, 1)	;
			}
		});
        shouChangLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!isLogin()) {
					Toast.makeText(mContext, "未登录，不能收藏", 5000).show();
				} else {
					//开始收藏
					if (movieBean != null) {
						requestShouChang(initRequestMap(movieBean));
					}
				}
			}
		});
        shareLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//分享
				Intent intent = new Intent(mContext,ShareToWeiboActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("shareContent", movieBean.getMovieName());
				bundle.putString("goodsUrl", movieBean.getShopUrl());
				intent.putExtras(bundle);
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			}
		});
        taoGouLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			startActivity(mContext, TaoGouActivity.class, 0)	;
			}
		});
        
        lookBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
		        
		      //去看看
				Intent intent=new Intent();
		        intent.setClass(mContext, WebViewActivity.class);
		        Bundle bundle = new Bundle();
		        bundle.putString("url", movieBean.getShopUrl());
		        bundle.putString("whichBuyType", "groupShop");
		        intent.putExtras(bundle);
//		        intent.putExtra("url", groupBuyGoods.getShopUrl());
		        startActivity(intent);
		        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		        }
		});
        
	}

	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub
		String resultMessage;
		try {
			resultMessage = response.getString("message");
			Toast.makeText(mContext, resultMessage, 5000).show();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	private void requestShouChang(Map<String, String> map) {

		IRequest request = new JSONReq("collect",map);
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
				showDialog("正在收藏...");
			}
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
						getDataToResolve(response);
				} else if (IResponse.Fail==result) {
					Toast.makeText(mContext, "收藏失败", 5000).show();
				}
					missDialog();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
//				super.onFailure(e, response);
				missDialog();
//				Log.e("GROUP", response);
				Toast.makeText(mContext, response, 5000).show();
//				missProgressBar();
			}
			
		});
	
		
	}
	
	private Map<String, String> initRequestMap(Movie movieBean) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("userId", preferences.getString("userId", ""));//用户id
		map.put("name", movieBean.getMovieName());//商品名字
		map.put("smallImage", movieBean.getSmallImage());//小图片
		map.put("bigImage", movieBean.getBigImage());//大图片
		map.put("place", movieBean.getPlace());//地点
		map.put("telephone", movieBean.getTelephone());//电话
		map.put("shopUrl", movieBean.getShopUrl());//商家地址
		map.put("description", "");//描述
		
		return map;
	}
	
	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(mContext, MovieActivity.class, 1);
		}
		return false;
	}
}
